package com.example.app;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity{

    private static final String TAG = "MainActivity";
    private WebView webView;

    private MqttUtil mqttUtil;


    private View toolNav;

    private BottomSheetBehavior<LinearLayout> bottomSheetBehavior;
    private View overlay;
    private RecyclerView recyclerView;
    private InfoAdapter adapter;
    private EditText etNewInfo;
    private List<String> infoList = new ArrayList<>();
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolNav = findViewById(R.id.tool_nav);
        webView = findViewById(R.id.activity_main_webview);


        overlay = findViewById(R.id.overlay);
        LinearLayout bottomSheet = findViewById(R.id.bottom_sheet);
        bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
        recyclerView = findViewById(R.id.recycler_view);
        etNewInfo = findViewById(R.id.et_new_info);


        // 设置初始数据
        infoList.add("示例信息 1");
        infoList.add("示例信息 2");
        infoList.add("示例信息 3");

        // 设置RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new InfoAdapter(infoList);
        recyclerView.setAdapter(adapter);


        WebSettings webSettings = webView.getSettings();


        adapter.setOnItemClickListener((view, position) -> {
            String selectedInfo = infoList.get(position);
            ToastUtil.showToast(MainActivity.this, "你选择了: " + selectedInfo);
        });

        // 设置底部面板行为
        bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_EXPANDED) {
                    showOverlay();
                } else if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                    hideOverlay();
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                overlay.setAlpha(slideOffset);
            }
        });

        // 设置按钮点击事件
        findViewById(R.id.btn_toggle_panel).setOnClickListener(v -> togglePanel());
        findViewById(R.id.btn_close).setOnClickListener(v -> hidePanel());
        overlay.setOnClickListener(v -> hidePanel());

        // 添加信息按钮

        findViewById(R.id.btn_add).setOnClickListener(v -> addNewInfo());


        // 启用JavaScript和DOM存储
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);

        // 允许加载混合内容（HTTP/HTTPS）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); // 允许所有混合内容
            // 或使用+WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE（兼容模式）
        }

        // 设置WebViewClient以处理页面加载
        webView.setWebViewClient(new WebViewClient());

        // 加载目标网址（注意：需添加"http://"前缀）
        webView.loadUrl("http://192.168.0.1:5000");

        mqttUtil = MqttUtil.getInstance(this);
        mqttUtil.setConnectionListener(new MqttUtil.MqttConnectionListener() {
            @Override
            public void onMqttConnected() {
                runOnUiThread(() -> {
                    Log.i(TAG, "MQTT Connected");
                });
            }
            @Override
            public void onMqttDisconnected() {
                runOnUiThread(() -> {
                    Log.e(TAG, "MQTT Disconnected");
                });
            }
            @Override
            public void onMqttMessageReceived(String topic, String message) {
                Log.d("MQTT", "Received: " + topic + " - " + message);
                // 处理接收到的消息
            }
            @Override
            public void onMqttError(String error) {
                runOnUiThread(() -> {
                    Log.e(TAG, "MQTT Error: " + error);
                });
            }
        });
        mqttUtil.connect();
        requestPermissions();

    }
    //发布信息
    private void publishData() {
        MqttUtil.getInstance(this).publishMessage("/map", "Hello from Android!");
    }
    private void togglePanel() {
        if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
            hidePanel();
        } else {
            showPanel();
        }
    }
    private void showPanel() {
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
    }

    private void hidePanel() {
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
    }

    private void showOverlay() {
        overlay.setVisibility(View.VISIBLE);
    }

    private void hideOverlay() {
        overlay.setVisibility(View.GONE);
    }

    private void addNewInfo() {
        String newInfo = etNewInfo.getText().toString().trim();
        if (!newInfo.isEmpty()) {
            infoList.add(0, newInfo); // 添加到列表开头
            adapter.notifyItemInserted(0);
            recyclerView.scrollToPosition(0);
            etNewInfo.setText("");
        }
    }

    // RecyclerView适配器
    public static class InfoAdapter extends RecyclerView.Adapter<InfoAdapter.InfoViewHolder> {

        private List<String> infoList;
        private OnItemClickListener onItemClickListener;

        public InfoAdapter(List<String> infoList) {
            this.infoList = infoList;
        }
        //条目点击监听
        public void setOnItemClickListener(OnItemClickListener listener) {
            this.onItemClickListener = listener;
        }

        @NonNull
        @Override
        public InfoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_info, parent, false);
            return new InfoViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull InfoViewHolder holder, int position) {
            holder.tvInfo.setText(infoList.get(position));

            // 设置整个条目的点击事件
            holder.itemView.setOnClickListener(v -> {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(v, position);
                }
            });

            // 设置删除按钮点击事件
            holder.btnDelete.setOnClickListener(v -> {
                infoList.remove(position);
                notifyItemRemoved(position);
            });
        }

        @Override
        public int getItemCount() {
            return infoList.size();
        }

        class InfoViewHolder extends RecyclerView.ViewHolder {
            TextView tvInfo;
            ImageButton btnDelete;

            public InfoViewHolder(@NonNull View itemView) {
                super(itemView);
                tvInfo = itemView.findViewById(R.id.tv_info);
                btnDelete = itemView.findViewById(R.id.btn_delete);
            }
        }

        // 点击监听接口
        public interface OnItemClickListener {
            void onItemClick(View view, int position);
        }
    }
    private void requestPermissions() {
        String[] permissions = new String[]{
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE/*,
        Manifest.permission.READ_SMS,
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.READ_PHONE_NUMBERS,
        Manifest.permission.SCHEDULE_EXACT_ALARM,
        Manifest.permission.USE_EXACT_ALARM*/
        };
        ActivityCompat.requestPermissions(
                this,
                permissions,
                101
        );
    }

}
